'''
Created on Jan 18, 2010

@author: madsk
'''

from __future__ import with_statement
from PIL import Image
import os
from PyQt4 import QtGui
import StringIO

class MultiImage(object):
    def __init__(self, path=None, size=None):
        super(MultiImage, self).__init__()
        self._preview = None
        self._pixmap = None
        self._path = path
        self._size = size
        
        if path != None and size != None:
            self.loadFromFile(path, size)
        
    def loadFromFile(self, path, desired_size):
        # Set properties.
        self._path = path
        self._size = desired_size
        
        # Create the preview version if necessary.
        preview_path = path + '.preview'
        if os.path.exists(preview_path):
            self._preview = Image.open(preview_path)
        else:
            # TODO: In creating the preview CF could be employed.
            original = Image.open(path)
            size = self._adjust_size_to_maintain_aspect(original.size, desired_size)
            self._preview = original.resize(size, Image.NEAREST)
            self._preview.save(preview_path, 'JPEG')
            del original
            
        # Load pixmap version.
        self._previewToPixmap()

    def _adjust_size_to_maintain_aspect(self, original_size, desired_size):
        scale = float(desired_size[0])/original_size[0]
        if original_size[1] * scale <= desired_size[1]:
            height = int(original_size[1] * scale)
            if height > desired_size[1]:
                height = desired_size[1]
            return (desired_size[0], height)
        else:
            scale = float(desired_size[1])/original_size[1]
            width = int(original_size[0] * scale)
            if width > desired_size[0]:
                width = desired_size[0]
            return (width, desired_size[1])
    
    def _previewToPixmap(self):
        file = StringIO.StringIO()
        self._preview.save(file, 'ppm')
        contents = file.getvalue()
        file.close()
        self._pixmap = QtGui.QPixmap()
        self._pixmap.loadFromData(contents)
        
    def original(): #@NoSelf
        def fget(self):
            return Image.open(self._path)
        return locals()
    original = property(**original())    
        
    def preview(): #@NoSelf
        def fget(self):
            return self._preview
        def fset(self, value):
            self._preview = value
            self._previewToPixmap()
        def fdel(self):
            del self._preview
        return locals()
    preview = property(**preview())
    
    def pixmap(): #@NoSelf
        def fget(self):
            return self._pixmap
        return locals()
    pixmap = property(**pixmap())
    
    def path(): #@NoSelf
        def fget(self):
            return self._path
        return locals()
    path = property(**path())
